//
//  SGBaseViewController.m
//  EatNumber
//
//  Created by zg.shao on 14/12/19.
//  Copyright (c) 2014年 kuwo.cn. All rights reserved.
//

#import "SGBaseViewController.h"

static NSString *kMusicSwitch = @"kMusicSwitch";

@interface SGBaseViewController () {
    UIButton *_musicBtn;    // 音效
}

@end

@implementation SGBaseViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        if (![[NSUserDefaults standardUserDefaults] objectForKey:kMusicSwitch]) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kMusicSwitch];
        }
        
        _musicOn = [[NSUserDefaults standardUserDefaults] boolForKey:kMusicSwitch];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMusicSwitchImage:) name:UPDATE_SOUND_IMAGE_NOTIFICATION object:nil];
    }
    
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initMusicControlBtns];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)initMusicControlBtns {
    _musicBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_musicBtn setFrame:CGRectMake(20, 10, 40, 40)];
    
    if (_musicOn) {
        [_musicBtn setImage:[UIImage imageNamed:@"music_on"] forState:UIControlStateNormal];
    } else {
        [_musicBtn setImage:[UIImage imageNamed:@"music_off"] forState:UIControlStateNormal];
    }
    
    [_musicBtn addTarget:self action:@selector(setMusicState) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_musicBtn];
}

- (void)setMusicState {
    [[NSUserDefaults standardUserDefaults] setBool:!_musicOn forKey:kMusicSwitch];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_SOUND_IMAGE_NOTIFICATION object:[NSNumber numberWithBool:!_musicOn]];
}

- (void)updateMusicSwitchImage:(NSNotification *)aNotification {
    _musicOn = [[aNotification object] boolValue];
    if (_musicOn) {
        [_musicBtn setImage:[UIImage imageNamed:@"music_on"] forState:UIControlStateNormal];
    } else {
        [_musicBtn setImage:[UIImage imageNamed:@"music_off"] forState:UIControlStateNormal];
    }
}
@end
